import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { v4 as uuidv4} from 'uuid';
import { ElMessageBox,ElMessage } from 'element-plus'
import router from '@/router'
import storage from '@/utils/storage'
import {Base64} from 'js-base64'
import i18n from '@/lang'

const http = axios.create({
  baseURL: '/dev',
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})
export const commonUrl = '';
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    let uuid = localStorage.getItem('uuid');
    if (!uuid) {
      uuid = uuidv4();
      localStorage.setItem('uuid', uuid+'');
    }
    config.headers['uuid'] = uuid;
    if(storage.getItem('currentRateName')){
      config.headers['switchRate'] = storage.getItem('currentRateName');
    }
    if(storage.getItem('currentLanguage')){
      config.headers['switchLanguage'] = storage.getItem('currentLanguage')
      config.headers['lang'] = storage.getItem('currentLanguage')
    }else{
      config.headers['lang'] = 'cn'
    }
    const accessToken = localStorage.getItem('accessToken')
    if (accessToken) {
      config.headers.Authorization = accessToken
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('===> response:',response);
    const { code, msg } = response.data
    if (code === '00000') {
      return response.data
    }
    // 响应数据为二进制流处理
    if (response.data instanceof ArrayBuffer) {
      return response
    }

    if (code === 'A0230') {
      ElMessageBox.confirm(i18n.global.t('request.authFail'),i18n.global.t('tip'), {
        confirmButtonText: i18n.global.t('confirm'),
        cancelButtonText: i18n.global.t('cancel'),
        type: 'warning'
      }).then(() => {
        // const userStore = useUserStoreHook()
        // userStore.resetToken().then(() => {
        //   location.reload()
        // })
        const redirectQuery = Base64.encode(router.currentRoute.value.fullPath)
        router.push({path:'/login',query:{redirect: redirectQuery}})
      })
    }else{
      ElMessage.error(msg || i18n.global.t('request.sysError'))
    }


    return Promise.reject(new Error(msg || 'Error'))
  },
  (error: any) => {
    if (error.data) {
      const { code, msg } = error.data
      // token 过期,重新登录
      if (code === 'A0230') {
        ElMessageBox.confirm(i18n.global.t('request.authFail'),i18n.global.t('tip'),  {
          confirmButtonText: i18n.global.t('confirm'),
          cancelButtonText: i18n.global.t('cancel'),
          type: 'warning'
        }).then(() => {
          // const userStore = useUserStoreHook()
          // userStore.resetToken().then(() => {
          //   location.reload()
          // })
          router.push('/login')
        })
      } else {
        ElMessage.error(msg || i18n.global.t('request.sysError'))
      }
    }
    return Promise.reject(error.message)
  }
)
export const Method = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete'
};
export default http
